<?php

namespace app\common\model;

use DateTime;

trait TimeCommon
{

    /**
     * 根据日期,计算出跟时间相关的参数
     *
     * @param [type] $termId
     * @param [type] $date
     * @return void
     */
    public function getTimeDetail(string $date, $termId = null)
    {
        $table = [];
        //确定学期
        if ($termId) {
            $term = Term::get($termId);
        } else {
            $term = Term::getDefaultTerm($date);
        }
        if (!$term) {
            $table['status'] = false;
            $table['errmsg'] = "无法确定学期,请联系管理员补充学期信息";
            return $table;
        }
        $table['term'] = $term;
        $dateObj = date_create($date);
        //确定查询周次
        $classWewk = date_diff(date_create($term->start_date), $dateObj);

        if ($classWewk->invert == 1 || $classWewk->days > 150) {
            $table['status'] = false;
            $table['errmsg'] = '默认学期配置有误,指定的日期不在学期的范围内';
            return $table;
        }

        //转换查询周次和星期
        $classWewk = 1 << (intval($classWewk->days / 7));
        $week = date('w', $dateObj->getTimeStamp());
        if ($week == 0)
            $week = 7;
        else
            $week = intval($week);
        $table['date'] = date_format($dateObj, 'Y-m-d');
        $table['class_week'] = $classWewk;
        $table['week'] = $week;
        $table['status'] = true;

        return $table;
    }

    /**
     * 将表示日期的字符串转为对应的DateTime对象
     *
     * @param string $date
     * @return void
     */
    // public function TranslateDate(string $date)
    // {
    //     switch ($date) {
    //         case "前天":
    //         case "前日":
    //             return date_sub(date_create(), new DateInterval("P2D"));
    //         case "昨天":
    //         case "昨日":
    //             return date_sub(date_create(), new DateInterval("P1D"));
    //         case "今日":
    //         case "今天":
    //             return date_create();
    //         case "明天":
    //         case "明日":
    //             return date_add(date_create(), new DateInterval("P1D"));
    //         case "后天":
    //             return date_add(date_create(), new DateInterval("P2D"));
    //         default:
    //             $match = [];
    //             if (preg_match("/(?:\(d{4})[\/\-])?(\d{1,2})[\/\-]\(d{1,2})|(?:\(d{4})年)?(\d{1,2})月((\d{1,2})日/", $date, $match)) {
    //                 $now= new DateTime();
    //                 if ($match[1]){
    //                     return $now->setDate($match[1],$match[2],$match[3]);
    //                 } else if ($match[2]){
    //                     return $now->setDate($now,$match[2],$match[3]);
    //                 }
    //                 $now= new DateTime();
    //             } else {
    //                 return false;
    //             }
    //     }
    // }
}
